package com.xiaoy.core.bpm.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;

import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;

import com.xiaoy.core.bpm.api.IProcessPerform;
import com.xiaoy.core.bpm.api.IProcessPerformBuilder;
import com.xiaoy.core.bpm.engine.entity.InstanceProcessVO;
import com.xiaoy.core.bpm.engine.entity.ProcessInstantiate;
import com.xiaoy.core.bpm.engine.entity.ProcessNodeVO;
import com.xiaoy.core.bpm.engine.entity.ProcessTask;
import com.xiaoy.core.bpm.simple.entity.ProcessDefine;
import com.xiaoy.core.bpm.simple.entity.ProcessNode;
import com.xiaoy.core.bpm.simple.service.ProcessNodeService;
import com.xiaoy.dao.DaoUtil;
import com.xiaoy.page.PageEasy;
@Namespace("/bpm")
@Results({
	@Result(name = "start", location = "/${jsp}", type = "dispatcher") ,
})
public class BpmAction extends BpmBaseAction{

	private File processZip;
	private String processZipFileName; 				// 上传文件的文件名
	private String processZipContentType; 			// 上传文件的类型
	
	private ProcessDefine processDefine;
//	private InstanceProcessVO process;
	private ProcessNode processNode;
	
	/**
	 * 流程定义的list
	 * @return
	 */
	public void deploymentList (){
		try {
			
//			List<ProcessDefineVO>ProcessDefines = //processDefineService.deploymentProcessList();
			
//			setAttribute("definitions", workFlow.getAllProcessDefinitions());
			
			List<ProcessDefine>ProcessDefines = processDefineService.deploymentProcessList();
//			setAttribute("processDefines",ProcessDefines );
			PageEasy<ProcessDefine> page = new PageEasy<ProcessDefine>();
			page.setRows(ProcessDefines);
			page.setTotal(ProcessDefines.size());
			renderJson(page);
			
		}catch (Exception e) {
			e.printStackTrace();
		}
		
//		return "deploymentlist";
	} 

	
	public String deploymentProcess () {
		
		try {
			System.out.println("deploymentProcess:"+processZip+"-----"+processZipFileName);
			System.out.println("processDefine:"+processDefine.getName()+"-----"+processDefine.getFormUrl());
			
//			workFlow.defineProcess(processDefine.getName(), new FileInputStream(processZip));
			processDefineService.deploymentProcess(processDefine, new FileInputStream(processZip),processZipFileName);
	
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return "deploymentprocess";
	}
	
	public String updateDeploymentProcess () {
		
		return "";
	}
	
	/**
	 * 发起流程
	 * @return
	 */
	public String start () {
		try {
//			System.out.println("process-->"+processDefine.getName()+"--"+processDefine.getProcessDefineKey());
			long id = getParameterLong("id");
			ProcessDefine p =  processDefineService.getProcessDefineBy("id",id);
			

			if ("1".equals(p.getFormType())) {
				
				// 设置为自定义的表单页面，跳转到指定的页面
				jsp = p.getFormUrl();
			}else {
				
				String path = "";
				
				
				if ("1".equals(p.getApprovalType())) {
					// 整个流程只有一个表单
					jsp = p.getFormUrl();;
					
				}else {
					// 每个节点可能都有自己的表单
					
					
				}
			}
			
			setAttribute("processDefine", p);
			
//			ProcessInstantiate instance =  workFlow.createProcessInstanceById(process);
			
		}catch (Exception e) {
			e.printStackTrace();
		}
		return "start";
	}
	@Resource
	private DaoUtil dao;
	public String started () {
		try {
//			System.out.println("process-->"+processDefine.getName()+"--"+processDefine.getProcessDefineKey());
			
			long id = getParameterLong("id");
			ProcessDefine p =  processDefineService.getProcessDefineBy("id",id);
			
			
			String applyUser = getCurrentUser();		// 申请人 为当前用户	
			
			//String applyUser = getParameter("applyUser");	// 申请人
			
			System.out.println(p.getProcessDefineKey()+" - "+applyUser);
			
			
			
//			if(approvalType) {
//				
//			}
			
			if ("1".equals(p.getFormType())) {
				
				InstanceProcessVO vo = new InstanceProcessVO();
				// 设置为自定义的表单页面，每个节点有直接的处理方式
				// 也许有预处理的事件
				IProcessPerform preform = IProcessPerformBuilder.getHeadler("", "");
				
				
				preform.commitBefore();
				
				preform.receiveFormDataBefore();
				
				
				// 调度业务数据 
				Map m = filterParametersPrefix("f_");
				
				preform.receiveFormDataAfter(m);
				
				vo.addParam("applyUser", applyUser);
				vo.setKey(p.getProcessDefineKey());
				
				ProcessInstantiate instant = processInstanceService.startProcessInstance(vo);
				
				m.put("instance_id", instant.getProcessInstanceId());
				
				preform.commitAfter();
				
//				dao.save(ConfigTable.Base.ACCOUNT, m);
			}else {
				
				// 生成的页面
				
				
			}
//			jsp = getParameter("formUrl");
//			ProcessInstantiate instance =  workFlow.createProcessInstanceById(process);
//			request.setAttribute("instance", instance);
		}catch (Exception e) {
			e.printStackTrace();
		}
		return "started";
	}
	@Resource
	private ProcessNodeService processNodeService;
	public void settingNodes () {
		
		String defineId = getParameter("defineId");
		
		
//		boolean flag = processNodeService.isGenerateProcessNodes(defineId);
		List<ProcessNode> nodes = processNodeService.findProcessNodesByDefineId(defineId);
		// 是否生成过数据
		if (nodes.size()>0) {
			// 已经生成过数据了
			renderJson(nodes);
		}else {
			List<ProcessNodeVO> vos = workFlow.getProcessNodesByDefineId(defineId);
			renderJson(vos);
		}
	}
	
	
	public void synNodes () {
		String defineId = getParameter("defineId");
		try {
			processNodeService.generateProcessNodesByDefineId(defineId);
		} catch (Exception e) {
			renderText("0");
			e.printStackTrace();
			return ;
		}
		renderText("1");
	}
	
	public String findNodeById () {
		
//		String defineId = getParameter("defineId");
		
		String nodeId = getParameter("nodeId");
		
		processNodeService.findProcessNodesByDefineId(defineId);
		
	}
	
	public String allProcessNodes () {
		
		long id = getParameterLong("id");
		ProcessDefine p =  processDefineService.getProcessDefineBy("id",id); 
		
		List<ProcessNodeVO> tasks = workFlow.getProcessNodesByDefineId(p.getProcessDefineId());
		
		//
		
		setAttribute("tasks", tasks);
		return "allTasks";
	}

	public void updateNode () {
		
		try {
			processNodeService.save(processNode);
		} catch (Exception e) {
			renderText("0");
			e.printStackTrace();
		}
		renderText("1");
	}
	
	public String approval () {
		
		return "approval";
	}
	
	/**
	 * 我的待办
	 * @return
	 */
	public String myTasks () {
		
		String username = getParameter("username");
		List<ProcessTask> tasks = workFlow.getTaskByUsername(username);
		setAttribute("tasks", tasks);
		return "mytasks";
	}
	
	public String myTask () {
		
		String instanceId = getParameter("");
		
		
		return "myTask";
	}
	
	
	
	
	/**
	 * 流程图
	 * 
	 */
	public void processImage () {
		
//		ProcessDefineVO vo = workFlow.getProcessDefinitionByDeployMentId(getParameter("id"));
		
		InputStream is = workFlow.getProcessImageByProcessDefineId(getParameter("defineId"));
		try {
			setAttribute("image", is);
			
			ServletOutputStream out = response.getOutputStream();
			
			byte[] b = new byte[1024]; 
		      int len = -1; 
		      while((len = is.read(b, 0, 1024)) != -1) {
		    	  out.write(b, 0, len);  
		      }
		      
		} catch (IOException e) {
			e.printStackTrace();
		}
//		return "processImage";
	}
	
	public void dycProcessImage () {
		
		InputStream is = workFlow.getProcessImageByInstanceId(getParameter("id"));
		try {
			
			ServletOutputStream out = response.getOutputStream();
			
			byte[] b = new byte[1024]; 
		      int len = -1; 
		      while((len = is.read(b, 0, 1024)) != -1) {
		    	  out.write(b, 0, len);  
		      }
		      
		} catch (IOException e) {
			e.printStackTrace();
		}
//		return "processImage";
	}
	
	
	
	public String processInstanceList () {
		
//		String defineId = getParameter("id");
//		ProcessDefineVO vo = workFlow.getProcessDefinitionByDeployMentId(getParameter("id"));
		
		List<ProcessInstantiate> pis = workFlow.getProcessInstancesByDefineId(getParameter("defineId"));
		setAttribute("pis", pis);
		return "processInstanceList";
	}
	
	
	// 设置流程的所欲的节点
	public String processSetting () {
		
		String id = getParameter("id");
		
		
		workFlow.getProcessNodesByDefineId(id);
		
		return "processSetting";
		
	}
	
	public void settingNodeProcessTree () {
		
		List<ProcessDefine>pds = processDefineService.getAll();
		
		String result = "[";
		for (ProcessDefine pd : pds) {
			result += "{"+fieldToJson("id",pd.getId()+"")+","+fieldToJson("text", pd.getName());
			List<ProcessNode> nodes = processNodeService.findProcessNodesByDefineId(pd.getProcessDefineId());
			
			if (nodes.size()>0) {
				
				result += ",\"children\":[";
				for (ProcessNode node:nodes) {
					result += "{"+fieldToJson("id",node.getId()+"")+","+fieldToJson("text", node.getNodeDefineName()+"("+ node.getName()+")")+"},";
				}
				result = result.substring(0,result.length()-1);
				result += "]";
			}else {
				
			}
			result +="},";
		}
		result = result.substring(0,result.length()-1);
		result += "]";
		System.out.println(result);
		renderText(result);
	}
	
	private String fieldToJson (String key,String value) {
		return "\""+key+"\""+":\""+value+"\"";
	}
	
	
	public ProcessNode getProcessNode() {
		return processNode;
	}

	public void setProcessNode(ProcessNode processNode) {
		this.processNode = processNode;
	}

	public File getProcessZip() {
		return processZip;
	}

	public void setProcessZip(File processZip) {
		this.processZip = processZip;
	}

	public String getProcessZipFileName() {
		return processZipFileName;
	}

	public void setProcessZipFileName(String processZipFileName) {
		this.processZipFileName = processZipFileName;
	}

	public String getProcessZipContentType() {
		return processZipContentType;
	}

	public void setProcessZipContentType(String processZipContentType) {
		this.processZipContentType = processZipContentType;
	}

	public ProcessDefine getProcessDefine() {
		return processDefine;
	}

	public void setProcessDefine(ProcessDefine processDefine) {
		this.processDefine = processDefine;
	}
}


